%% Transaction cost
clear Q_ret_Spread_VW LS_ret_Spread_VW
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INSERT SORTING VARIABLE AND RETURNS HERE
Sort_Var = Stock_PRisk; 
returns1 = (call_buying_ret_TC10(1:end,:)); % Return of buying delta-hedged call at transaction cost of 10%
returns5 = (call_writing_ret_TC10(1:end,:)); % Return of selling delta-hedged call at transaction cost of 10% 
Weight = MVO;
Factors = [mktrf_m(2:end) smb_m(2:end) hml_m(2:end) umd_m(2:end) strdl_m(2:end) dvix_m(2:end)];
rf = rf_m(2:end)*100;
NW = 4;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
% Long-short strategy
for i = 1:size(Sort_Var,1)
    id1m = ~isnan(Sort_Var(i,:)+returns1(i,:)+Weight(i,:));  
    Returns = returns1(i,:); Returns(:,find(id1m == 0)) = [];
    W = Weight(i,:);W(:, find(id1m == 0)) = [];
    Betas_1M = Sort_Var(i,:); Betas_1M(:,find(id1m == 0)) = [];
      
    q_points_Spread_1M = prctile(Betas_1M, [0 20 40 60 80 100], 2);
    
    for j = 1: size(q_points_Spread_1M,2)-1  
       Q_ret_Spread_VW(i,j) = Returns (1,Betas_1M > q_points_Spread_1M(1,j) & Betas_1M...
         <= q_points_Spread_1M(1,j+1))*(W(1,Betas_1M > q_points_Spread_1M(1,j)...
         & Betas_1M <= q_points_Spread_1M(1,j+1))./nansum(W(1,Betas_1M >...
         q_points_Spread_1M(1,j) & Betas_1M <= q_points_Spread_1M(1,j+1))))';
    end   
end

Q_ret_VW1 = Q_ret_Spread_VW(:,1);
clear Q_ret_Spread_VW i id1m Returns W Betas_1M q_points_Spread_1M j 

% Long-short strategy
for i = 1:size(Sort_Var,1)
    id1m = ~isnan(Sort_Var(i,:)+returns5(i,:)+Weight(i,:));  
    Returns = returns5(i,:); Returns(:,find(id1m == 0)) = [];
    W = Weight(i,:);W(:, find(id1m == 0)) = [];
    Betas_1M = Sort_Var(i,:); Betas_1M(:,find(id1m == 0)) = [];
      
    q_points_Spread_1M = prctile(Betas_1M, [0 20 40 60 80 100], 2);
    
    for j = 1: size(q_points_Spread_1M,2)-1  
       Q_ret_Spread_VW(i,j) = Returns (1,Betas_1M > q_points_Spread_1M(1,j) & Betas_1M...
         <= q_points_Spread_1M(1,j+1))*(W(1,Betas_1M > q_points_Spread_1M(1,j)...
         & Betas_1M <= q_points_Spread_1M(1,j+1))./nansum(W(1,Betas_1M >...
         q_points_Spread_1M(1,j) & Betas_1M <= q_points_Spread_1M(1,j+1))))';
    end   
end

Q_ret_VW5 = Q_ret_Spread_VW(:,5);
clear Q_ret_Spread_VW i id1m Returns W Betas_1M q_points_Spread_1M j 

% RESULTS
Result_SingleSort = nan(2,1);
LS_ret_Spread_VW = Q_ret_VW5 + Q_ret_VW1;
Result_SingleSort(1,1) = nanmean(LS_ret_Spread_VW);
stats_Spread_VW = nwest(LS_ret_Spread_VW,ones(size(LS_ret_Spread_VW)),NW); 
Result_SingleSort(2,1) = stats_Spread_VW.tstat;

clear id1m id1M id1MM Returns W Betas_1M q_points_Spread_1M Sort_Var ...
      i j k stats_Spread_EW Q_ret_Spread_W Q_ret_Spread_W Weight returns1 returns5 ...
      stats_Spread_FFC_VW stats_Spread_FFC_EW stats_Spread_VW Factors rf NW ...
      LS_ret_Spread_EW LS_ret_Spread_VW Factors rf